package cn.t.service.user;

import cn.t.core.mode.YesNoEnum;
import cn.t.core.service.ServiceImpl;
import cn.t.dto.user.ResourceInfoDTO;
import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.model.user.RoleResourceDO;
import cn.t.repository.user.RoleResourceRepository;
import cn.t.user.event.UserRedisClearEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static cn.t.constants.Constants.REDIS_KEY__RESOURCE_ROLE_VO;


/**
 * 部门信息表领域服务
 *
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class RoleResourceService extends ServiceImpl<RoleResourceDO, RoleResourceRepository> {

    public void assignRights(Long roleId, List<ResourceInfoDTO> resourceInfoList) {
        boolean result = removeByRoleId(roleId);

        if (resourceInfoList != null) {
            resourceInfoList.forEach(resourceInfoDTO -> {
                RoleResourceDO roleResourceDO = new RoleResourceDO();
                roleResourceDO.setRoleId(roleId);
                roleResourceDO.setResourceId(resourceInfoDTO.getId());
                roleResourceDO.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
                roleResourceDO.setGmtCreated(new Date());
                repository.add(roleResourceDO);
            });
        }
        // 清理缓存
        String redisKey = String.format(REDIS_KEY__RESOURCE_ROLE_VO, roleId);
        applicationEventPublisher.publishEvent(new UserRedisClearEvent(redisKey, redisKey));
    }

    public List<RoleResourceDO> findByRoleId(Set<Long> roleIdList) {

        if (roleIdList == null) {
            return null;
        }
        List<RoleResourceDO> ret = new ArrayList<>();

        for (Long roleId : roleIdList) {
            List<RoleResourceDO> roleResourceList = findByRoleId(roleId);
            if (roleResourceList == null || roleResourceList.isEmpty()) {
                continue;
            }
            ret.addAll(roleResourceList);
        }

        return ret;
    }

    public List<RoleResourceDO> findByRoleId(Long roleId) {
        RoleResourceDO template = new RoleResourceDO();
        template.setRoleId(roleId);
        template.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        template.setIsDeleted(YesNoEnum.FALSE);

        return repository.findByModel(template, 0, 10000, "id", "asc");
    }


    public boolean removeByRoleId(Long roleId) {
        return repository.removeByRoleId(roleId);
    }
    public boolean removeByResourceId(Long resourceId) {return repository.removeByResourceId(resourceId);
    }

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;



}
